package com.example.springbootfastjson2.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.springbootfastjson2.model.User;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @program: springboot-fastjson2
 * @description: 实体类转化成json字符串   使用fastjson
 * @author: XianJin.Lu
 * @create: 2021-09-08 16:21
 **/
public class ObjToJsonString {
    public static void main(String[] args) {
        User user=new User("张三",18);

        Map<String,Object> map2 = new HashMap<>();
        String s5= "{\"name\":\"李四\",\"age\":18}";
        map2.put("msg", s5);
        String s2 = JSONObject.toJSONString(map2);
        System.out.println(s2);

        //实体类转化成json字符串
        String s = JSONObject.toJSONString(user);
        System.out.println(s);

        //json字符串转化为  json对象
        JSONObject jsonObject = JSONObject.parseObject(s);
        System.out.println(jsonObject);
        System.out.println(jsonObject.get("name"));    //等价于    System.out.println(user.getName());


        //字符串 转化为json对象的好处是 可以通过get 方法  获取value
        String user2=   "{\"name\":\"李四\",\"age\":18}";
        //json对象
        JSONObject jsonObject1 = JSONObject.parseObject(user2);
        System.out.println(jsonObject1.get("name"));


        //转化为json对象
        JSONObject jsonObject2 = JSON.parseObject(user2);
        System.out.println(jsonObject2.get("name"));

        //字符串转化为Object对象
        Object obj = JSON.parse(user2);
        HashMap<String, Object> map = new HashMap<>();
        map.put("用户2",obj);


        Object o2 = map.get("用户2");
        String s1 = JSON.toJSONString(o2);
        JSONObject jsonObject3 = JSON.parseObject(s1);
        System.out.println(jsonObject3.get("name"));


        //字符串就是String对象
        map.put("用户3",user2);
        String o3= (String)map.get("用户3");
        JSONObject jsonObject4 = JSON.parseObject(o3);
        System.out.println(jsonObject4.get("name"));



    }
}
